package info.batcloud.fanli.core.service.impl;

import info.batcloud.fanli.core.dto.CommissionOrderAddDTO;
import info.batcloud.fanli.core.component.LxkClientFactory;
import info.batcloud.fanli.core.constants.PddConstatns;
import info.batcloud.fanli.core.domain.DdkTraceInfo;
import info.batcloud.fanli.core.enums.CommissionOrderStatus;
import info.batcloud.fanli.core.enums.EcomPlat;
import info.batcloud.fanli.core.pdd.PddApp;
import info.batcloud.fanli.core.service.CommissionOrderService;
import info.batcloud.fanli.core.service.DdkService;
import info.batcloud.fanli.core.service.SystemSettingService;
import info.batcloud.fanli.core.settings.DdkAuthSetting;
import info.batcloud.fanli.core.settings.DdkSetting;
import info.batcloud.laxiaoke.open.request.jd.union.DdkOauthOrderListIncrementGetRequest;
import info.batcloud.laxiaoke.open.request.pdd.TokenRefreshRequest;
import info.batcloud.laxiaoke.open.response.pdd.TokenRefreshResponse;
import info.batcloud.pdd.sdk.PddClient;
import info.batcloud.pdd.sdk.domain.ddk.Order;
import info.batcloud.pdd.sdk.request.ddk.OauthOrderListIncrementGetRequest;
import info.batcloud.pdd.sdk.response.ddk.OauthOrderListIncrementGetResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class DdkServiceImpl implements DdkService {

    private static final Logger logger = LoggerFactory.getLogger(DdkServiceImpl.class);

    @Inject
    private PddClient pddClient;

    @Inject
    @Qualifier(PddConstatns.DDK_UNION)
    private PddApp pddApp;

    @Inject
    private CommissionOrderService commissionOrderService;

    @Inject
    private SystemSettingService systemSettingService;

    @Override
    public void fetchOrder(OrderFetchParam param) {
        logger.info("开始同步多多客订单，参数:" + param);
        Date startTime = param.getStartUpdateTime();
        Date endTime = param.getEndUpdateTime();
        int totalCount = 0;
        while(true) {
            Date _endTime = DateUtils.addHours(startTime, 24);
            param.setStartUpdateTime(startTime);
            param.setEndUpdateTime(_endTime);
            startTime = _endTime;
            int count = doFetchOrder(param);
            if (_endTime.after(endTime)) {
                break;
            }
            totalCount += count;
        }
        logger.info("多多客订单同步完成,共同步：" + totalCount);
    }

    public int doFetchOrder(OrderFetchParam param) {
        logger.info("开始同步多多客订单，参数:" + param);
        OauthOrderListIncrementGetRequest request = new OauthOrderListIncrementGetRequest();
        request.setStartUpdateTime(param.getStartUpdateTime().getTime() / 1000);
        request.setEndUpdateTime(param.getEndUpdateTime().getTime()  / 1000);
        if (StringUtils.isNotBlank(param.getPid())) {
            request.setPid(param.getPid());
        }
        int pageSize = 50;
        request.setPageSize(pageSize);
        request.setPage(1);
        DdkAuthSetting ddkAuthSetting = systemSettingService.findActiveSetting(DdkAuthSetting.class);
        DdkSetting ddkSetting = systemSettingService.findActiveSetting(DdkSetting.class);
        request.setPid(ddkSetting.getPid());
        OauthOrderListIncrementGetResponse response = pddClient.execute(request, ddkAuthSetting.getAccessToken());
        int totalCount = response.getData().getTotalCount();
        int maxPage = (totalCount + pageSize - 1) / pageSize;
        int page = maxPage;
        while (true && maxPage > 0) {
            logger.info("同步页数：" + page);
            request.setPage(page--);
            response = pddClient.execute(request, ddkAuthSetting.getAccessToken());
            if (response.getData() != null
                    && response.getData().getOrderList() != null) {
                List<CommissionOrderAddDTO> coList = new ArrayList<>();
                for (Order order : response.getData().getOrderList()) {
                    /**
                     * 订单状态： -1 未支付;
                     * 0-已支付；1-已成团；
                     * 2-确认收货；3-审核成功；
                     * 4-审核失败（不可提现）；5-已经结算；
                     * 8-非多多进宝商品（无佣金订单）;10-已处罚
                     * */
                    if (order.getOrderStatus() == 8) {
                        continue;
                    }
                    if (StringUtils.isBlank(order.getCustomParameters())) {
                        continue;
                    }
                    DdkTraceInfo traceInfo;
                    try {
                        traceInfo = DdkTraceInfo.fromJson(order.getCustomParameters());
                    } catch (Exception e) {
                        continue;
                    }
                    CommissionOrderAddDTO co = new CommissionOrderAddDTO();
                    co.setUserId(traceInfo.getUserId());
                    co.setItemId(order.getGoodsId());
                    co.setItemNum(order.getGoodsQuantity());
                    co.setPlatSettledTime(new Date(order.getOrderReceiveTime() * 1000));
                    /**
                     * 佣金比例是 千分比，这里保存为百分比
                     * */
                    co.setEstimateCommissionRate(order.getPromotionRate() / 10);
                    /**
                     * 佣金,单位为分，转化为元。
                     * */
                    co.setEstimateCommissionFee(order.getPromotionAmount() / 100);
                    /**
                     * 佣金比例是 千分比，这里保存为百分比
                     * */
                    co.setCommissionRate(order.getPromotionRate() / 10);
                    /**
                     * 佣金,单位为分，转化为元。
                     * */
                    co.setCommissionFee(order.getPromotionAmount() / 100);
                    co.setItemTitle(order.getGoodsName());
                    co.setCreateTime(new Date(order.getOrderCreateTime() * 1000));
                    co.setEcomPlat(EcomPlat.PDD);
                    co.setOrderNo(order.getOrderSn());
                    co.setPayFee(order.getOrderAmount() / 100);
                    co.setPrice(order.getGoodsPrice() / 100);
                    co.setShopTitle("拼多多");
                    co.setStatus(determineCommissionOrderStatus(order.getOrderStatus()));
                    coList.add(co);
                }
                Collections.reverse(coList);
                commissionOrderService.saveCommissionOrderList(coList);
                logger.info("同步订单数量：" + coList.size());
                if (coList.size() < pageSize) {
                    break;
                }
            } else {
                break;
            }
        }
        logger.info("多多客订单同步完成,共同步：" + totalCount);
        return totalCount;
    }

    @Override
    public boolean refreshAccessToken() {
        return true;
    }

    private static CommissionOrderStatus determineCommissionOrderStatus(int status) {
        /**
         * 订单状态： -1 未支付;
         * 0-已支付；1-已成团；
         * 2-确认收货；3-审核成功；
         * 4-审核失败（不可提现）；5-已经结算；
         * 8-非多多进宝商品（无佣金订单）;10-已处罚
         * */
        switch (status) {
            case 10:
            case 4:
                return CommissionOrderStatus.INVALID;
            case -1:
                return CommissionOrderStatus.WAIT_PAY;
            case 0:
            case 1:
            case 3:
            case 2:
                return CommissionOrderStatus.PAID;
            case 5:
                return CommissionOrderStatus.WAIT_SETTLE;
            default:
                return CommissionOrderStatus.INVALID;
        }
    }
}
